//
//  STContentViewModel.swift
//  iPhone
//
//  Created by Toj on 11/17/23.
//

import Foundation

class STContentViewModel: NSObject {
    
    var commentsResponse: (()->Void)?
    
    var commentViewModel: STTabViewModel?
    
    func response(comments count: Int) {
        commentViewModel?.tip = count.to_k
        commentsResponse?()
    }
}

extension STContentViewModel {
    
    func request(tabs completion: @escaping (([STTabViewModel], STTabViewModel?) -> Void)) {
        commentViewModel = nil
        
        let tabs = STResponse<[STTabModel]>.deserialize(from: kTabsJSON_all)?.data ?? []
        
        var defaultViewModel: STTabViewModel?
        var viewModels = [STTabViewModel]()
        guard tabs.count > 1 else {
            let viewModel = STTabViewModel(title: "videoTAB_details".localized())
            defaultViewModel = viewModel
            viewModels.append(viewModel)
            completion(viewModels, defaultViewModel)
            return
        }
        
        var index = 0
        for tab in tabs {
            let viewModel = STTabViewModel(tab: tab)
            viewModel.index = index
            viewModels.append(viewModel)
            index += 1
            
            if viewModel.isSelected { defaultViewModel = viewModel }
            guard viewModel.type == .comment else { continue }
            commentViewModel = viewModel
        }
        if defaultViewModel == nil { defaultViewModel = viewModels.first }
        completion(viewModels, defaultViewModel)
        
        guard commentViewModel != nil else { return }
        requestComments()
    }
    
    func requestComments() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: { [weak self] in
            let commentCount = Int(arc4random_uniform(10000) + 651)
            self?.response(comments: commentCount)
        })
    }
}
